<template>
	<div id="my-chat">
		<div id="chat">
			<template>
				<div class="sidebar">
					<card  :parent_data.sync="parent_data"></card>
					<list :user-list="userList"  :parent_data="parent_data"></list>
				</div>
				<div class="main">
					<message :session="session" :user="user" :parent_data.sync="parent_data" :user-list="userList"></message>
					<text_ :session="session" :parent_data="parent_data" :conn='conn'></text_>
				</div>
			</template>
		</div>
		<!--<input type="text" style="border: 1px solid black;" v-model="username" />
		<input type="password" style="border: 1px solid black;" v-model="password" />

		<button class="btn" @click="resist">注册</button>
		<button class="btn" @click="login">登录</button>
		<button class="btn" @click="sendMessage">发送消息</button>
		<button class="btn" @click="listRooms">获取聊天室列表</button>
		<button class="btn" @click="addFriends">添加好友</button>
		<button class="btn" @click="joinRoom">加入聊天室</button>
		<button class="btn" @click="getList">获取好友列表</button>
		<button class="btn" @click="getInfo">获取用户</button>-->

	</div>
</template>

<script>
	import store from './components/store';
	import card from './components/card';
	import list from './components/list';
	import text_ from './components/text';
	import message from './components/message';
	export default {
		data() {
			let serverData = store.fetch();
			return {
				isLogin: false,
				username: '1a6e9032751a9247f8e74a31814182ba',
				password: '0e1a7fe83afa96c0120a41f4224397c4',
				// 登录用户
				user: {},
				// 用户列表
				userList: [],
				// 会话列表
				sessionList: serverData.sessionList,
				// 搜索key
				parent_data: {
					search: '',
					sessionIndex: 0, // 选中的会话Index
					currentItem: null,
				},
				conn: null,
				Emoji: WebIM.Emoji,
				my_user_info: JSON.parse(sessionStorage.getItem('my_user_info'))
			}
		},
		computed: {
			session() {
				return this.sessionList[this.parent_data.sessionIndex];
			}
		},
		mounted() {
			this.getFridens();
			let self = this;
			var conn = new WebIM.connection({
				isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
				https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:',
				url: WebIM.config.xmppURL,
				heartBeatWait: WebIM.config.heartBeatWait,
				autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
				autoReconnectInterval: WebIM.config.autoReconnectInterval,
				apiUrl: WebIM.config.apiURL,
				isAutoLogin: true
			});
			setTimeout(() => {
				this.$message.success('连接成功!');
				this.chatListen();
				this.getInfo()
			}, 0)
			this.conn = conn;
			window.conn = conn;

		},
		watch: {
			// 每当sessionList改变时，保存到localStorage中
			sessionList: {
				deep: true,
				handler() {
					console.log(this.sessionList)
					store.save({
						user: this.user,
						userList: this.userList,
						sessionList: this.sessionList
					});
				}
			}
		},
		components: {
			card,
			list,
			message,
			text_
		},
		methods: {
			chatListen() {
				let self = this;
				conn.listen({
					onTextMessage: function(message) {
						console.log(message)
						if(self.userList.length == 0) {
							setTimeout(() => {
								self.receiveMessage(message);
							}, 1000)
						} else {
							self.receiveMessage(message);
						}
					},
					onEmojiMessage: function(message) { //收到表情消息
						// 当为WebIM添加了Emoji属性后，若发送的消息含WebIM.Emoji里特定的字符串，connection就会自动将
						// 这些字符串和其它文字按顺序组合成一个数组，每一个数组元素的结构为{type: 'emoji(或者txt)', data:''}
						// 当type='emoji'时，data表示表情图像的路径，当type='txt'时，data表示文本消息
						console.log(message);
						self.setEmoji(message);

						//			        var data = message.data;
						//			        for(var i = 0 , l = data.length ; i < l ; i++){
						//			            console.log(data[i]);
						//			        }
					},
					onPictureMessage: function(message) {
						if(self.userList.length == 0) {
							setTimeout(() => {
								self.receivePicture(message);
							}, 2000)
						} else {
							self.receivePicture(message);
						}
					},
					onPresence: function(message) {
						self.sloveAddFriend(message);
					},
					onRoster: function(message) {
						console.log(message)
					},
				})
			},
			receiveMessage(message) {
				let self = this;
				for(let i = 0; i < self.userList.length; i++) {
					if(message.from == self.userList[i].name) {
						if(message.from != self.parent_data.currentItem.userId) {
							let obj = self.userList[i];
							obj.notRead++
								self.userList.splice(i, 1, obj)
						}
						self.sessionList[i].messages.push({
							text: message.data,
							date: (message.delay ? message.delay : new Date()),
							type: 1
						})
					}
				}
			},
			setEmoji(message) {
				let self = this;
				let arr_ = message.data;
				let pre = ''
				let arr = arr_.map(item => {
					if(item.type == 'txt') {
						return item;
					} else if(item.type == 'emoji') {
						let ar = item.data.split('/')
						console.log(ar)
						return {
							type: item.type,
							data: ar[ar.length - 1]
						}
					}
				})
				for(let item of arr) {
					if(item.type == 'txt') {
						pre += item.data
					} else if(item.type == 'emoji') {
						let p = require('./components/assets/faces/' + item.data);
						pre += `<img src="${p}" class="emoji"  />`
					}
				}

//				this.html = pre;
				
				for(let i = 0; i < self.userList.length; i++) {
					if(message.from == self.userList[i].name) {
						if(message.from != self.parent_data.currentItem.userId) {
							let obj = self.userList[i];
							obj.notRead++
							self.userList.splice(i, 1, obj)
						}
						self.sessionList[i].messages.push({
							text: pre,
							date: (message.delay ? message.delay : new Date()),
							type: 1
						})
					}
				}
				
				console.log(arr)

			},
			receivePicture(message) {
				let self = this;
				for(let i = 0; i < self.userList.length; i++) {
					if(message.from == self.userList[i].name) {
						if(message.from != self.parent_data.currentItem.userId) {
							let obj = self.userList[i];
							obj.notRead++
								self.userList.splice(i, 1, obj)
						}
						self.sessionList[i].message.push({
							text: message.url,
							date: message.delay,
							type: 2
						})
					}
				}
			},
			sloveAddFriend(e) {
				//收到联系人订阅请求的处理方法，具体的type值所对应的值请参考xmpp协议规范
				if(e.type === 'subscribe') {
					/*同意添加好友操作的实现方法*/
					conn.subscribed({
						to: e.from,
						message: '[resp:true]'
					});
					conn.subscribe({ //需要反向添加对方好友
						to: e.from,
						message: '[resp:true]'
					});
				}
			},
			getFridens() {
				let self = this;
				this.httptool.ajaxPost(this.apis.getFridens, null, res => {
					if(res.data && res.data.length > 0) {
						self.userList = res.data.map(item => {
							return {
								userId: item.loginCounter,
								nickName: item.realName,
								name: item.loginCounter,
								messages: [],
								img: item.headImgUrl,
								notRead: 0

							}
						});
					}
					if(self.userList.length > 0) {
						this.getSessionList();
						this.parent_data.currentItem = self.userList[0];
					} else {
						this.userList = [];
						this.sessionList = [];
					}

				})
			},
			getSessionList() {
				let self = this;
				if(store.fetch() && store.fetch().sessionList && store.fetch().sessionList.length < 1) {
					self.sessionList = self.userList.map(item => {
						return {
							userId: item.userId,
							messages: [],
							name: item.userId
						}
					});
					return;
				}
				//去重
				self.sessionList = [];
				let local_sessionList = store.fetch().sessionList;
				self.sessionList = self.userList.map(item => {
					for(let item_ of local_sessionList) {
						if(item.userId == item_.userId) {
							return item_;
						}
					}
					return {
						userId: item.userId,
						messages: [],
						name: item.userId
					}
				});
			},
			getInfo() {
				let obj = JSON.parse(sessionStorage.getItem('hxAccount'));
				this.username = obj.account;
				this.password = obj.password;
				setTimeout(() => {
					this.login();
				}, 100)

			},
			resist() {
				var options = {
					username: '1179696632',
					password: '123',
					nickname: '123',
					appKey: WebIM.config.appkey,
					success: function() {},
					error: function() {},
					apiUrl: WebIM.config.apiURL
				};
				this.conn.registerUser(options);
			},
			login() {
				let self = this;
				this.username = JSON.parse(sessionStorage.getItem('hxAccount')).account;
				this.password = JSON.parse(sessionStorage.getItem('hxAccount')).password;
				var options = {
					apiUrl: WebIM.config.apiURL,
					user: this.username,
					pwd: this.password,
					appKey: WebIM.config.appkey,
					success: function(token) {
						self.$message.success('登录成功！');
						self.user = {
							id: token.user.username,
							name: token.user.username,
							pwd: self.password,
							img: self.my_user_info.iconUrl
						}
						if(store.fetch().userList.length > 0) {
							setTimeout(() => {
								self.isLogin = true;
							}, 0)
						} else {
							setTimeout(() => {
								console.log(token)
								self.user = {
									id: token.user.username,
									name: token.user.username,
									pwd: self.password,
									img: self.my_user_info.iconUrl
								}
							}, 100)
						}
					}
				};
				this.conn.open(options);
			},
			getList() {
				let self = this;
				conn.getRoster({
					success: function(roster) {
						//获取好友列表，并进行好友列表渲染，roster格式为：
						/** [
						      {
						        jid:'asemoemo#chatdemoui_test1@easemob.com',
						        name:'test1',
						        subscription: 'both'
						      }
						    ]
						*/
						self.userList = roster.map(item => {
							return {
								userId: item.name,
								name: item.name,
								messages: [],
								img: item.headImgUrl,
								notRead: 0

							}
						});

						self.getSessionList(roster);

						self.isLogin = true;
						console.log(roster)
					},
				});
			},

			sendMessage() {
				// 单聊发送文本消息
				var id = conn.getUniqueId(); // 生成本地消息id
				var msg = new WebIM.message('txt', id); // 创建文本消息
				msg.set({
					msg: 'message content', // 消息内容
					to: '7db95b4642316b6d467aab14f3c2a82f', // 接收消息对象（用户id）
					roomType: false,
					success: function(id, serverMsgId) {
						console.log('send private text Success');
						this.$message.success(serverMsgId);
					},
					fail: function(e) {
						console.log("Send private text error");
					}
				});
				msg.body.chatType = 'singleChat';
				conn.send(msg.body);
			},
			listRooms() {
				var option = {
					apiUrl: 'https://a1.easemob.com',
					pagenum: 1, // 页数
					pagesize: 20, // 每页个数
					success: function(list) {
						console.log(list);
					},
					error: function() {
						console.log('List chat room error');
					}
				};
				conn.getChatRooms(option);
			},
			addFriends() {

				conn.subscribe({
					to: '222',
					// Demo里面接收方没有展现出来这个message，在status字段里面
					message: '加个好友呗!'
				});
			},
			joinRoom() {
				conn.joinChatRoom({
					roomId: '62645762850817' // 聊天室id
				});

			}

		}
	}
</script>

<style lang="less" scoped="scoped">
	#my-chat {
		height: ~'calc(100vh - 200px)';
		min-height: 700px;
		#chat {
			overflow: hidden;
			border-radius: 3px;
			margin: 20px auto;
			/*width: 900px;*/
			width: 100%;
			height: 100%;
			.sidebar,
			.main {
				height: 100%;
			}
			.sidebar {
				float: left;
				width: 300px;
				color: #f4f4f4;
				background-color: #2e3238;
			}
			.main {
				position: relative;
				overflow: hidden;
				background-color: #fff;
			}
			.m-text {
				position: absolute;
				width: 100%;
				bottom: 0;
				left: 0;
			}
			.m-message {
				height: ~'calc(100% - 190px)';
			}
			.btn {
				padding: 6px 18px;
			}
		}
	}
</style>